package ${initProjectVo.packageNameValue}.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;



import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

    /**
    * @author Open-Free-Team Faye.Wang
    * @version 1.0
    * @date 2020/9/4 21:53
    * @Description redis 工具类
    */
@Component
public class JRedisUtils {
    private static Logger logger = LoggerFactory.getLogger(JRedisUtils.class);

    @Autowired
    RedisTemplate<Object,Object> redisDataTemplate;

    static RedisTemplate<Object,Object> redisTemplate;

    @PostConstruct
    public void init(){
        redisTemplate = this.redisDataTemplate;
    }


    /**
    * set value to redis
    * @param key
    * @param value
    * @param seconds
    */
    public static void setKeyValue(String key, String value, int seconds){
        ValueOperations jedis =  redisTemplate.opsForValue();
        try {
            jedis.set(key, value,seconds,TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    public static void setKeyValue(String key, String value){
        ValueOperations jedis =  redisTemplate.opsForValue();
        try {
            jedis.set(key,value);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }



    /**
    * get value for redis
    * @param key
    * @return
    */
    public static String  getKeyValue(String key){
        String result = null;
        ValueOperations jedis =  redisTemplate.opsForValue();
        try {
            result = jedis.get(key).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }
    public static void del(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
